<template>
  <view class="page-container">
    <GlobalTopBar ref="topBarRef" class="topbars" :isLeft="true">
      <template #title
        ><text>{{ fromDttas.id ? '编辑地址' : '添加地址' }}</text></template
      >
    </GlobalTopBar>
    <view class="page_content">
      <!-- 底部按钮 -->
      <view class="btnb">
        <button @click="doSaveUserAddress">保存</button>
      </view>
      <!-- 跳转信息 -->
      <view class="ulbox">
        <view class="ul">
          <view
            class="li"
            :class="{ ac: index === ulList.length - 1 }"
            v-for="(item, index) in ulList"
            :key="index + 1"
          >
            <view
              class="libox"
              :class="[
                { ac: index === ulList.length - 1 },
                { border_b: index < ulList.length - 1 },
              ]"
            >
              <view class="cen_text">
                <text class="t1">{{ item.text }}</text>
              </view>
              <!-- 输入框 -->
              <view class="srkinp">
                <template v-if="item.text != '地区'">
                  <input
                    @change="(val) => changeFun(val, item.key)"
                    v-if="index < ulList.length - 1"
                    :type="item.type || 'text'"
                    :maxlength="item.maxlength || 99999"
                    v-model="item.value"
                    :placeholder="item.placeholder"
                  />
                  <textarea
                    class="textarea"
                    @input="(val) => changeFun(val, item.key)"
                    v-else
                    style="height: 120rpx"
                    type="text"
                    v-model="item.value"
                    :placeholder="item.placeholder"
                  />
                </template>
                <template v-else>
                  <input
                    v-if="!item.value"
                    @click="openNativeMap"
                    disabled
                    type="text"
                    :placeholder="item.placeholder"
                  />
                  <view v-else>
                    {{ item.value }}
                  </view>
                </template>
              </view>
              <!-- 定位 -->
              <view
                class="dw"
                v-if="item.text === '地区'"
                @click="openNativeMap"
              >
                <uni-icons
                  type="location"
                  size="25"
                  color="#0291F6"
                ></uni-icons>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 文字 -->
      <view class="btext">
        <image :src="`${store.imgDomain}my_text.png`" mode="scaleToFill" />
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, reactive } from 'vue';
import { useCounterStore } from '@/store';
import { onLaunch, onShow, onUnload } from '@dcloudio/uni-app';
import request from '@/utils/request';
import { validatePhone } from '@/utils/validate';

const store = useCounterStore();
const userInfo = ref({});

// 参数
const fromDttas = reactive({
  id: '',
  contact_name: '',
  phone: '',
  region_name: '',
  province_name: '',
  city_name: '',
  district_name: '',
  address: '',
  longitude: '',
  latitude: '',
  is_default: 0,
});
//
const ulList = computed(() => [
  {
    text: '姓名',
    value: fromDttas.contact_name,
    placeholder: '请输入姓名',
    key: 'contact_name',
  },
  {
    text: '手机号',
    value: fromDttas.phone,
    placeholder: '请输入手机号',
    key: 'phone',
    maxlength: 11,
    type: 'number',
  },
  {
    text: '地区',
    value: `${
      fromDttas.province_name + fromDttas.city_name + fromDttas.district_name
    }`,
    placeholder: '请选择省市区县',
  },
  {
    text: '详细地址',
    value: fromDttas.address,
    key: 'address',
    placeholder: '小区、街道、写字楼',
  },
]);

// 输入框改变触发
const changeFun = (val, key) => {
  console.log(val, key);
  fromDttas[key] = val.detail.value;
};

// 存储选择的位置信息
const selectedLocation = ref(null);

// 调起微信原生地图选择页面（自带搜索功能）
const openNativeMap = () => {
  // 检查位置权限（可选，提升体验）
  uni.getSetting({
    success: (settingRes) => {
      console.log('settingRes', settingRes);

      // 若未授权位置权限，先申请授权
      if (!settingRes.authSetting['scope.userLocation']) {
        uni.authorize({
          scope: 'scope.userLocation',
          success: (res) => {
            launchMap(); // 授权成功后调起地图
          },
          fail: () => {
            // 引导用户到设置页开启权限
            uni.showModal({
              title: '权限申请',
              content: '需要获取您的位置以显示附近地点，请开启位置权限',
              confirmText: '去设置',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  uni.openSetting(); // 打开小程序设置页
                }
              },
            });
          },
        });
      } else {
        launchMap(); // 已授权，直接调起地图
      }
    },
  });
};

// 核心：调用 uni.chooseLocation 调起原生地图
const launchMap = () => {
  uni.chooseLocation({
    // 可选：设置地图初始中心位置（经纬度）
    // latitude: 39.9042, // 示例：北京纬度
    // longitude: 116.4074, // 示例：北京经度
    success: (res) => {
      getTencentMapAddress(res.latitude, res.longitude, res.name);
    },
    fail: (err) => {
      // 处理失败（如用户取消选择）
      if (err.errMsg !== 'chooseLocation:fail cancel') {
        uni.showToast({
          title: '地图选择失败',
          icon: 'none',
        });
      }
    },
  });
};

// 【腾讯地图】经纬度获取地信息
const getTencentMapAddress = async (latitude, longitude, name) => {
  const data = await request('wxapp/common/getTencentMapAddress', {
    location: `${latitude},${longitude}`,
  });
  fromDttas.longitude = longitude;
  fromDttas.latitude = latitude;
  fromDttas.province_name = data.ad_info.province;
  fromDttas.city_name = data.ad_info.city;
  fromDttas.district_name = data.ad_info.district;
  fromDttas.region_name = name;
  fromDttas.address = name;
};

// 保存会员服务地址数据
const doSaveUserAddress = async () => {
  console.log(fromDttas);

  if (!fromDttas.contact_name) {
    uni.showToast({
      title: '请输入姓名',
      icon: 'none',
    });
    return;
  } else if (!fromDttas.phone) {
    uni.showToast({
      title: '请输入手机号',
      icon: 'none',
    });
    return;
  } else if (!validatePhone(fromDttas.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none',
    });
    return;
  } else if (!fromDttas.province_name) {
    uni.showToast({
      title: '请选择地区',
      icon: 'none',
    });
    return;
  } else if (!fromDttas.address) {
    uni.showToast({
      title: '请输入详细地址',
      icon: 'none',
    });
    return;
  }
  const data = await request(
    'wxapp/user/doSaveUserAddress',
    {
      ...fromDttas,
    },
    'POST',
  );
  uni.navigateBack({
    delta: 1,
  });
};
uni.$on('datas', (data) => {
  fromDttas.id = data.id;
  fromDttas.is_default = data.is_default;
  for (let key in fromDttas) {
    fromDttas[key] = data[key];
  }
});
onLaunch(() => {});
onUnload(() => {
  uni.$off('datas');
});
</script>

<style lang="scss" scoped>
.topbars {
  background-color: #ffffff;
}
.topinfo {
  position: relative;
  box-sizing: border-box;
  padding: 30rpx;
  display: flex;
  align-items: center;
  .yhimg {
    position: absolute;
    top: 0;
    left: 0;
    width: 750rpx;
    height: 127rpx;
    z-index: 0;
  }
  .hadeimg {
    display: block;
    margin: 20rpx auto;
    border: 1px solid #fff;
    border-radius: 50%;
    width: 125rpx;
    height: 125rpx;
    position: relative;
    z-index: 1;
  }
}
.ulbox {
  margin-top: 20rpx;
  padding: 20rpx;
  .ul {
    border: 1rpx solid #437ef6;
    border-radius: 20rpx;
    box-sizing: border-box;
    padding: 0 20rpx;
    background-color: #fff;
    .libox {
      display: flex;
      align-items: center;
      padding: 25rpx 10rpx;
      box-sizing: border-box;

      &.ac {
        align-items: flex-start;
        border: none;
        align-items: none;
        flex-direction: column;
      }
      .srkinp {
        flex: 1;
      }
      .dw {
        padding: 0 20rpx;
      }
      .imgbox {
        width: 50rpx;
        height: 45rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        .img1 {
          width: 46rpx;
          height: 34rpx;
        }
        .img2 {
          width: 36rpx;
          height: 38rpx;
        }
        .img3 {
          width: 40rpx;
          height: 40rpx;
        }
        .img4 {
          width: 38rpx;
          height: 44rpx;
        }
        .img5 {
          width: 40rpx;
          height: 40rpx;
        }
        .img6 {
          width: 42rpx;
          height: 44rpx;
        }
      }
      .cen_text {
        position: relative;
        padding: 0 20rpx;
        // flex: 1;
        width: 15%;
        display: flex;
        justify-content: space-between;

        &::after {
          content: '*';
          position: absolute;
          top: 0;
          left: 0;
          color: red;
        }
        .t1 {
          white-space: nowrap;
        }
        .t2 {
          color: $uni-text-color-grey;
        }
      }
    }
  }
}
.btext {
  position: relative;
  margin-top: 35rpx;
  display: flex;
  justify-content: center;
  &::after {
    content: ' ';
    width: 100rpx;
    height: 1rpx;
    position: absolute;
    top: 50%;
    left: 140rpx;
    transform: translateY(-50%);
    background-color: #73adff;
  }
  &::before {
    content: ' ';
    width: 100rpx;
    height: 1rpx;
    position: absolute;
    top: 50%;
    right: 140rpx;
    transform: translateY(-50%);
    background-color: #73adff;
  }
  image {
    position: relative;
    display: block;
    opacity: 0.6;
    width: 185rpx;
    height: 38rpx;
  }
}
.page_content {
  position: relative;
  .btnb {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #fff;
    padding: 15rpx 30rpx;
    box-sizing: border-box;
    button {
      background-color: #0084f2;
      line-height: 70rpx;
      color: #fff;
      font-size: 30rpx;
      text-align: center;
      border-radius: 35rpx;
    }
  }
}
.textarea {
  border-radius: 20rpx;

  box-sizing: border-box;
  padding: 20rpx;
}
</style>
